<?php

namespace app\admin\service\user;

use app\common\model\user\User;
use app\common\model\user\UserGroup;
use tmcore\base\BaseService;
use tmcore\exceptions\ValidateException;

class GroupService extends BaseService
{
    /**
     * 获取分组列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $searchParam = [
            '%like%' => ['name']
        ];
        $where = self::getSearchData($searchParam, []);

        // 返回分页数据
        return UserGroup::page($where, self::getPageData(),'*', ['sort' => 'desc', 'id' => 'desc'],['user_count']);
    }

    /**
     * 添加分组
     * @param array $params
     * @return bool
     */
    public static function add(array $params)
    {
        self::beginTrans();
        try {
            $add_id = UserGroup::add([
                'name' => $params['name'],
                'remark' => $params['remark'] ?? '',
                'is_default' => $params['is_default'],
                'sort' => $params['sort'] ?? 0
            ],true);
            if(!$add_id) throw new \Exception('添加分组失败');
            if($params['is_default']) UserGroup::where([['id', '<>', $add_id]])->update(['is_default' => 0]);
            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 编辑分组
     * @param array $params
     * @return bool
     */
    public static function edit(array $params) : bool
    {
        self::beginTrans();
        try {
            UserGroup::edit([
                'name' => $params['name'],
                'remark' => $params['remark'],
                'is_default' => $params['is_default'],
                'sort' => $params['sort'] ?? 0
            ], $params['id']);
            if($params['is_default']) UserGroup::where([['id', '<>', $params['id']]])->update(['is_default' => 0]);
            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 删除分组
     * @param array $params
     * @return bool
     */
    public static function delete(array $params)
    {
        $count = User::where(['group_id' => $params['id']])->count();
        if($count) throw new ValidateException('分组已被用户使用，无法删除');
        return UserGroup::del($params['id']);
    }

    /**
     * 查看分组详情
     * @param $params
     * @return array
     */
    public static function detail($params) : array
    {
        return UserGroup::findOrEmpty($params['id'])->toArray();
    }

    /**
     * 分组数据
     * @return array
     */
    public static function getAllData()
    {
        return UserGroup::where([])
            ->field('id, name')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->select()
            ->toArray();
    }
}